package com.gitee.kamismile.stoneComEx.common.component.servlet;

import com.gitee.kamismile.stoneComEx.common.Constant;
import com.gitee.kamismile.stoneComEx.util.SecretCodeUtil;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import com.gitee.kamismile.stoneComEx.common.component.support.annotation.SecurityParameter;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

public class DecodeRequestBodyAdvice implements RequestBodyAdvice {


    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.getMethodAnnotation(SecurityParameter.class) != null
                && methodParameter.getParameterAnnotation(RequestBody.class) != null;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage request, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        SecurityParameter requestDecode = parameter.getMethodAnnotation(SecurityParameter.class);
        if (ValueUtils.isNull(requestDecode)) {
            return request;
        }
        boolean encode = requestDecode.inDecode();
        if(encode) {
            try {
                InputStream io = request.getBody();
                String data = StreamUtils.copyToString(io, Charset.forName("UTF-8"));
                return new DecodedHttpInputMessage(request.getHeaders(),
                        new ByteArrayInputStream(SecretCodeUtil.decrypt(data, Constant.SECODE,SecretCodeUtil.BLOWFISH).getBytes("UTF-8")));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return request;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

}
